package com.yonyou.sto.modules.ims.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yonyou.sto.common.api.CommonResult;
import com.yonyou.sto.common.domain.DownloadFile;
import com.yonyou.sto.common.domain.OpenBillBuilder;
import com.yonyou.sto.domain.InvoiceStatusEnums;
import com.yonyou.sto.domain.ManualStatusEnums;
import com.yonyou.sto.modules.ims.dto.*;
import com.yonyou.sto.modules.ims.mapper.ImsInvoiceMapper;
import com.yonyou.sto.modules.ims.model.*;
import com.yonyou.sto.modules.ims.service.*;
import com.yonyou.sto.modules.ums.model.UmsAdmin;
import com.yonyou.sto.modules.ums.model.UmsAdminRoleRelation;
import com.yonyou.sto.modules.ums.model.UmsNcOrg;
import com.yonyou.sto.modules.ums.service.*;
import com.yonyou.sto.modules.ums.service.impl.ConfigNameServicImpl;
import com.yonyou.sto.modules.ums.util.ImsInvoiceUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.Principal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author aegon
 * @since 2020-09-15
 */
@Service
@Transactional
public class ImsInvoiceServiceImpl extends ServiceImpl<ImsInvoiceMapper, ImsInvoice> implements ImsInvoiceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImsInvoiceServiceImpl.class);
    @Value("${yonyoucloud.app_id}")
    private String APP_ID;

    @Value("${yonyoucloud.domain}")
    private String DOMAIN;
    @Value("${yonyoucloud.red_url}")
    private String RED_URL;
    @Value("${yonyoucloud.cancel_url}")
    private String CANCEL_URL;
    @Resource
    private ImsInvoiceItemService imsInvoiceItemService;

    @Resource
    private UmsAdminService adminService;

    @Resource
    private ImsPartyAdminRelationService relationService;

    @Resource
    private UmsAdminOrgRelationService umsAdminOrgRelationService;

    @Resource
    private ImsPartyService partyService;

    @Resource
    private UmsNcOrgService orgService;

    @Resource
    private ImsReturnInvoiceService returnInvoiceSer;

    @Resource
    private ImsManualInvoiceService manualInvoiceService;

    @Resource
    private ImsBuyerService imsBuyerService;

    @Resource
    private ImsCancleInvoiceService imsCancleInvoiceService;

    @Resource
    private OpenBillBuilder openBillBuilder;

    @Resource
    private PushBillService pushBillService;

    @Resource
    private ConfigNameServic configNameServic;

    @Resource
    private UmsAdminRoleRelationService umsAdminRoleRelationService;

    @Override
    public ImsInvoice getOneByBillSn(String billSn) {
        QueryWrapper<ImsInvoice> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ImsInvoice::getBillSn, billSn);
        return getOne(wrapper);
    }

    @Override
    public CommonResult create(ImsInvoiceParam param) {

        ImsInvoice invoice = getOneByBillSn(param.getBillSn());

        if (invoice != null) {
            if (invoice.getStatus() == InvoiceStatusEnums.CANCEL.getCode() || invoice.getStatus() == InvoiceStatusEnums.RETURN.getCode() || invoice.getStatus() == InvoiceStatusEnums.RED.getCode()) {
                // 如果已存在单据且状态为已退回的单据则更新
                return updateBill(param);
            } else {
                return CommonResult.failed("系统中已存在该收款单号");
            }
        }

        if (param.getImsInvoiceItemParams().size() == 0) {
            // 单据明细为空则放到手工开票中
            return addManualInvoice(param);
        }

        ImsInvoice imsInvoice = new ImsInvoice();
        BeanUtils.copyProperties(param, imsInvoice);
        imsInvoice.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        imsInvoice.setStatus(1);
        CommonResult imsBuyerData = imsBuyerService.findByBuyerName(param.getBuyerName());
        if (imsBuyerData.getCode()==200){
            List<ImsBuyer> data = (  List<ImsBuyer>) imsBuyerData.getData();
            imsInvoice.setBuyerTaxSn(data.get(0).getBuyerTaxSn());
    }
        baseMapper.insert(imsInvoice);

        boolean success = imsInvoiceItemService.createBatchInvoiceItem(imsInvoice.getId(), param.getImsInvoiceItemParams());
        if (success) return CommonResult.success("接收单据成功!");
        else return CommonResult.failed("新增单据失败");
    }

    CommonResult addManualInvoice(ImsInvoiceParam param) {
        ImsManualInvoice manual = new ImsManualInvoice();
        BeanUtil.copyProperties(param, manual);
        manual.setStatus(ManualStatusEnums.REJECT.getCode());
        manual.setCreateUsername("admin");
        manual.setCreateNickname("admin");
        manual.setCreateTime(new Date());
        manualInvoiceService.save(manual);
        return CommonResult.success("接收单据成功!");
    }
    @Override
    public CommonResult revoke(String billSn) {

        ImsInvoice invoice = getOneByBillSn(billSn);
        if (invoice == null) return CommonResult.validateFailed("根据编号未找到该单据");
        if (invoice.getStatus() == InvoiceStatusEnums.SUCCESS.getCode() || invoice.getStatus() == InvoiceStatusEnums.HALF.getCode())
            return CommonResult.failed("已开票不能退回");
        invoice.setStatus(InvoiceStatusEnums.RETURN.getCode());
        baseMapper.updateById(invoice);

        return CommonResult.success("退回成功!");
    }

    @Override
    public CommonResult updateBill(ImsInvoiceParam param) {
        ImsInvoice invoice = getOneByBillSn(param.getBillSn());
        BeanUtils.copyProperties(param, invoice);
        invoice.setStatus(InvoiceStatusEnums.NOT.getCode());
        invoice.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        boolean result = updateById(invoice);

        if (result) imsInvoiceItemService.updateBatchInvoiceItem(invoice.getId(), param.getImsInvoiceItemParams());

        return CommonResult.success("更新成功");
    }

    @Override
    public CommonResult<Map<String, Object>> list(String username, Integer pageSize, Integer pageNum,String billSerial, String billSn,String billNo,String billCode, String sellerName, String buyerName, List<Integer> statusList, String startTime, String endTime,String djlx,String billType,String applyname,String ncName) {
        Map<String, Object> result = new HashMap<>();
        // 根据开票通知上面的公司和登录用户勾选的公司，当前登录人只展示自己对应的公司开票信息。
        UmsAdmin umsAdmin = adminService.getAdminByUsername(username);
        boolean isKF = false;
        if(umsAdmin!=null){
            List<UmsAdminRoleRelation> list = umsAdminRoleRelationService.list(new LambdaQueryWrapper<UmsAdminRoleRelation>().eq(UmsAdminRoleRelation::getAdminId, umsAdmin.getId()));
            if(list!=null&&list.size()>0){
                for (UmsAdminRoleRelation umsAdminRoleRelation: list) {
                        if ("10".equals(umsAdminRoleRelation.getRoleId())){
                            isKF = true;
                        }
                }
            }

        }

//        List<Long> partyIds = relationService.getPartyIdsByAdminId(umsAdmin.getId());
        List<String> partyIds = umsAdminOrgRelationService.getNcOrgByAdminId(umsAdmin.getId());


        QueryWrapper<ImsInvoice> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ImsInvoice> lambda = wrapper.lambda();
        if (!username.equals("admin") ) {
            if (CollUtil.isEmpty(partyIds)){
                Map<String, Object> result2 = new HashMap<>();
                // mp的分页插件用不了 只能自己分页
                List dtos = new ArrayList<InvoiceDto>();
                result2.put("list", dtos);
                result2.put("pageNum", pageNum);
                result2.put("pageSize", pageSize);
                result2.put("total", 0);

                return CommonResult.success(result2);
            }
            List<UmsNcOrg> parties = orgService.listByIds(partyIds);
            lambda.in(ImsInvoice::getSellerSn, parties.stream().map(UmsNcOrg::getCode).collect(Collectors.toList()));
        }
//        QueryWrapper<ImsInvoice> wrapper = new QueryWrapper<>();
//        LambdaQueryWrapper<ImsInvoice> lambda = wrapper.lambda();
//
//        if (!username.equals("admin") && CollUtil.isNotEmpty(partyIds)) {
//            List<ImsParty> parties = partyService.listByIds(partyIds);
//            lambda.in(ImsInvoice::getSellerSn, parties.stream().map(ImsParty::getSellerSn).collect(Collectors.toList()));
//        }

        if (StrUtil.isNotEmpty(billSerial)) lambda.like(ImsInvoice::getBillSerial, billSerial);

        if (StrUtil.isNotEmpty(billSn)) lambda.like(ImsInvoice::getBillSn, billSn);

        if (StrUtil.isNotEmpty(billNo)) lambda.like(ImsInvoice::getBillNo, billNo);

        if (StrUtil.isNotEmpty(billCode)) lambda.like(ImsInvoice::getBillCode, billCode);

        if (StrUtil.isNotEmpty(sellerName)) lambda.like(ImsInvoice::getSellerName, sellerName);

        if (StrUtil.isNotEmpty(buyerName)) lambda.like(ImsInvoice::getBuyerName, buyerName);

        if (StrUtil.isNotEmpty(billType)) lambda.like(ImsInvoice::getBillType, billType);

        if (StrUtil.isNotEmpty(applyname)) lambda.like(ImsInvoice::getApplyname, applyname);

        if(isKF){
            if(StrUtil.isNotBlank(umsAdmin.getNcid())){//客服
                String ncId = umsAdmin.getNcid();
                String[] ncIds = ncId.split(",");
                if(ncIds.length==0){
                    lambda.in(ImsInvoice::getDef5,ncId);
                }
                lambda.in(ImsInvoice::getDef5,ncIds);
                //lambda.like(ImsInvoice::getDef5,umsAdmin.getNcid());
            }
        }


        if (djlx != null) {
            lambda.eq(ImsInvoice::getDjlx, djlx);
        } else {
            lambda.in(ImsInvoice::getDjlx,"fp","ys","lp" );
        }

        lambda.in(ImsInvoice::getStatus, statusList);

        /**
         * allEq	基于 map 内容等于=
         ne	不等于<>
         gt	大于>
         ge	大于等于>=
         lt	小于<
         le	小于等于<=
         */
        if (StrUtil.isNotBlank(startTime))
            lambda.ge(ImsInvoice::getCreateTime, startTime);
        //lambda.ge(ImsInvoice::getCreateTime, DateUtil.parse(startTime, DatePattern.NORM_DATE_FORMAT));

        if (StrUtil.isNotBlank(endTime)) {
            if (DateUtil.isSameDay(DateUtil.parse(startTime, "yyyy-MM-dd"), DateUtil.parse(endTime, "yyyy-MM-dd"))) {
                Date date = DateUtil.parse(endTime, "yyyy-MM-dd");
                //Date date1 = DateUtil.offset(date, DateField.MILLISECOND, 1);//DateUtil.offset(date,DateField.DAY_OF_MONTH,1)
                Date date1 = DateUtil.offset(date,DateField.DAY_OF_MONTH,1);
                //Date date2 = DateUtil.offset(date1, DateField.MILLISECOND, -1);
                String format = DateUtil.format(date1, "yyyy-MM-dd");
                lambda.le(ImsInvoice::getCreateTime, format);
            } else {
                Date date = DateUtil.parse(endTime, "yyyy-MM-dd");
                //Date date1 = DateUtil.offset(date, DateField.MILLISECOND, 1);//DateUtil.offset(date,DateField.DAY_OF_MONTH,1)
                Date date1 = DateUtil.offset(date,DateField.DAY_OF_MONTH,1);
                //Date date2 = DateUtil.offset(date1, DateField.MILLISECOND, -1);
                String format = DateUtil.format(date1, "yyyy-MM-dd");
                lambda.le(ImsInvoice::getCreateTime, format);

            }
        }

        if(StrUtil.isNotBlank(ncName)){
            UmsAdmin user = adminService.getOne(new LambdaQueryWrapper<UmsAdmin>()
                    .like(UmsAdmin::getNickName, ncName)
            );
            if(user!=null){
                String ncId = user.getNcid();
                if(StrUtil.isNotBlank(ncId)){
                    String[] ncIds = ncId.split(",");
                    lambda.in(ImsInvoice::getDef5,ncIds);
                }
            }else{
                Map<String, Object> result1 = new HashMap<>();
                // mp的分页插件用不了 只能自己分页
                List dtos = new ArrayList<InvoiceDto>();
                result1.put("list", dtos);
                result1.put("pageNum", pageNum);
                result1.put("pageSize", pageSize);
                result1.put("total", 0);

                return CommonResult.success(result1);
            }

        }
        //lambda.le(ImsInvoice::getCreateTime, DateUtil.parse(endTime, DatePattern.NORM_DATE_FORMAT));
        //lambda.last("order by case status when 3 then 1 when 1 then 2 when 4 then 3 when 7 then 4 else 5 end ,create_time desc");

        for (Integer status:statusList) {
            /*if (!status.equals(1)){
                //lambda.orderByDesc(ImsInvoice::getApplydate,);
                lambda.last("order by applydate desc");
            }else {*/
                lambda.last("order by bill_sn asc");
            //}
        }

        List<ImsInvoice> invoices = list(wrapper);

        if (invoices.isEmpty()) {
            return CommonResult.validateFailed("暂无数据");
        }

        result.put("pageNum", pageNum);
        List<ImsInvoice> collect = invoices.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        List<String> ids = collect.stream().map(ImsInvoice::getId).collect(Collectors.toList());
        if (ids.isEmpty()){
            collect = invoices.stream().skip((1 - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
            ids = collect.stream().map(ImsInvoice::getId).collect(Collectors.toList());
            result.put("pageNum", 1);
            if(ids.isEmpty()){
                return CommonResult.failed("请重置");
            }
        }
        // 查出单据对应的单据明细
        //List<ImsInvoiceItem> items = imsInvoiceItemService.listByBillIds(ids);
        List<ImsInvoiceItem> items = imsInvoiceItemService.list(new LambdaQueryWrapper<ImsInvoiceItem>()
                .in(ImsInvoiceItem::getManualId, ids)
                .in(ImsInvoiceItem::getStatus, statusList)
                .last(" ORDER BY CAST(DEF6 AS number)")
        );
        List<ImsInvoiceItem> invoiceItemConfigName = getInvoiceItemConfigName(items);

        List<InvoiceDto> dtos = new ArrayList<>();

        collect.forEach(i -> {
            InvoiceDto dto = new InvoiceDto();
            BeanUtils.copyProperties(i, dto);
            dto.setInvoiceItems(invoiceItemConfigName.stream().filter(is -> is.getBillSn().equals(dto.getBillSn())).collect(Collectors.toList()));
            dto.setCreateTime(i.getCreateTime());
            String ncNameId = i.getDef5();
                if(StrUtil.isNotBlank(ncNameId)){
                    List<UmsAdmin> list = adminService.list(new LambdaQueryWrapper<UmsAdmin>()
                            .likeRight(UmsAdmin::getNcid, ncNameId)
                    );
                    if(list!=null&&list.size()>0){
                        if(list.get(0)!=null){
                            dto.setNcName(list.get(0).getNickName());
                        }
                    }
                }
            dtos.add(dto);
        });




        // mp的分页插件用不了 只能自己分页
        result.put("list", dtos);
        //result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("total", invoices.size());

        return CommonResult.success(result);
    }

    public List<ImsInvoiceItem> getInvoiceItemConfigName(List<ImsInvoiceItem> items){
        /*List<ImsInvoiceItem> collect1 = items.stream().map(m -> {
            if (StrUtil.isEmpty(m.getCustmatname())){
                m.setCustmatname(configNameServic.getCustCofigStringName(m));
            }
            return m;
        }).collect(Collectors.toList());
        imsInvoiceItemService.updateBatchById(collect1);*/
        return items;
    }

    @Override
    public CommonResult<Map<String, Object>> listNotice(String username, Integer pageSize, Integer pageNum, String billSn, String sellerName, String buyerName, String djlx, String startTime, String endTime) {

        // 根据开票通知上面的公司和登录用户勾选的公司，当前登录人只展示自己对应的公司开票信息。
        UmsAdmin umsAdmin = adminService.getAdminByUsername(username);
        List<String> partyIds = umsAdminOrgRelationService.getNcOrgByAdminId(umsAdmin.getId());

        QueryWrapper<ImsInvoice> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ImsInvoice> lambda = wrapper.lambda();
        if (!username.equals("admin") && CollUtil.isNotEmpty(partyIds)) {
            List<UmsNcOrg> parties = orgService.listByIds(partyIds);
            lambda.in(ImsInvoice::getSellerSn, parties.stream().map(UmsNcOrg::getCode).collect(Collectors.toList()));
        }
//        QueryWrapper<ImsInvoice> wrapper = new QueryWrapper<>();
//        LambdaQueryWrapper<ImsInvoice> lambda = wrapper.lambda();
//        if (!username.equals("admin") && CollUtil.isNotEmpty(partyIds)) {
//            List<UmsNcOrg> parties = orgService.listByIds(partyIds);
//            //List<ImsParty> parties = partyService.listByIds(partyIds);
//
//            lambda.in(ImsInvoice::getSellerSn, parties.stream().map(UmsNcOrg::getCode).collect(Collectors.toList()));
//        }

        if (StrUtil.isNotEmpty(billSn)) lambda.like(ImsInvoice::getBillSn, billSn);

        if (StrUtil.isNotEmpty(sellerName)) lambda.like(ImsInvoice::getSellerName, sellerName);

        if (StrUtil.isNotEmpty(buyerName)) lambda.like(ImsInvoice::getBuyerName, buyerName);

        if(StrUtil.isNotEmpty(djlx)){
            lambda.eq(ImsInvoice::getDjlx,djlx);
        }else {
            lambda.in(ImsInvoice::getDjlx,"fp","ys","lp");
        }

        lambda.in(ImsInvoice::getStatus,1);
        /**
         * allEq	基于 map 内容等于=
         ne	不等于<>
         gt	大于>
         ge	大于等于>=
         lt	小于<
         le	小于等于<=
         */
        if (StrUtil.isNotBlank(startTime))
            lambda.ge(ImsInvoice::getCreateTime, DateUtil.parse(startTime, DatePattern.NORM_DATE_FORMAT));

        if (StrUtil.isNotBlank(endTime))
            lambda.le(ImsInvoice::getCreateTime, DateUtil.parse(endTime, DatePattern.NORM_DATE_FORMAT));

        lambda.last("order by case status when 3 then 1 when 1 then 2 when 4 then 3 when 7 then 4 else 5 end ,create_time desc");

        List<ImsInvoice> invoices = list(wrapper);

        if (invoices.isEmpty()) {
            return CommonResult.validateFailed("暂无数据");
        }

        List<ImsInvoice> collect = invoices.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        List<String> ids = collect.stream().map(ImsInvoice::getId).collect(Collectors.toList());
        if (ids.isEmpty()) return CommonResult.failed();
        // 查出单据对应的单据明细
        List<ImsInvoiceItem> items = imsInvoiceItemService.listByBillIds(ids);

        List<InvoiceDto> dtos = new ArrayList<>();
        collect.forEach(i -> {
            InvoiceDto dto = new InvoiceDto();
            BeanUtils.copyProperties(i, dto);
            dto.setInvoiceItems(items.stream().filter(is -> is.getBillSn().equals(dto.getBillSn())).collect(Collectors.toList()));
            dto.setCreateTime(i.getCreateTime());
            dtos.add(dto);
        });

        Map<String, Object> result = new HashMap<>();
        // mp的分页插件用不了 只能自己分页
        result.put("list", dtos);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("total", invoices.size());

        return CommonResult.success(result);
    }

    @Override
    public CommonResult<Map<String, Object>> listApply(String username, Integer pageSize, Integer pageNum, String billSn, String sellerName, String buyerName,String djlx, Integer status, String startTime, String endTime) {

        // 根据开票通知上面的公司和登录用户勾选的公司，当前登录人只展示自己对应的公司开票信息。
        UmsAdmin umsAdmin = adminService.getAdminByUsername(username);
        List<String> partyIds = umsAdminOrgRelationService.getNcOrgByAdminId(umsAdmin.getId());


        QueryWrapper<ImsInvoice> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ImsInvoice> lambda = wrapper.lambda();
        if (!username.equals("admin") && CollUtil.isNotEmpty(partyIds)) {
            List<UmsNcOrg> parties = orgService.listByIds(partyIds);
            lambda.in(ImsInvoice::getSellerSn, parties.stream().map(UmsNcOrg::getCode).collect(Collectors.toList()));
        }
//        QueryWrapper<ImsInvoice> wrapper = new QueryWrapper<>();
//        LambdaQueryWrapper<ImsInvoice> lambda = wrapper.lambda();
//        if (!username.equals("admin") && CollUtil.isNotEmpty(partyIds)) {
//            List<UmsNcOrg> parties = orgService.listByIds(partyIds);
//            //List<ImsParty> parties = partyService.listByIds(partyIds);
//
//            lambda.in(ImsInvoice::getSellerSn, parties.stream().map(UmsNcOrg::getCode).collect(Collectors.toList()));
//        }

        if (StrUtil.isNotEmpty(billSn)) lambda.like(ImsInvoice::getBillSn, billSn);

        if (StrUtil.isNotEmpty(sellerName)) lambda.like(ImsInvoice::getSellerName, sellerName);

        if (StrUtil.isNotEmpty(buyerName)) lambda.like(ImsInvoice::getBuyerName, buyerName);

        if(StrUtil.isNotEmpty(djlx)){
            lambda.eq(ImsInvoice::getDjlx,djlx);
        }else {
            lambda.in(ImsInvoice::getDjlx,"fp","ys","lp");
        }

        if (status != null) {
            lambda.eq(ImsInvoice::getStatus, status);
        } else {
            lambda.in(ImsInvoice::getStatus,  3, 4,5,9);
        }
        /**
         * allEq	基于 map 内容等于=
         ne	不等于<>
         gt	大于>
         ge	大于等于>=
         lt	小于<
         le	小于等于<=
         */
        if (StrUtil.isNotBlank(startTime))
            lambda.ge(ImsInvoice::getCreateTime, DateUtil.parse(startTime, DatePattern.NORM_DATE_FORMAT));

        if (StrUtil.isNotBlank(endTime))
            lambda.le(ImsInvoice::getCreateTime, DateUtil.parse(endTime, DatePattern.NORM_DATE_FORMAT));

        lambda.last("order by case status when 3 then 1 when 1 then 2 when 4 then 3 when 7 then 4 else 5 end ,create_time desc");

        List<ImsInvoice> invoices = list(wrapper);

        if (invoices.isEmpty()) {
            return CommonResult.validateFailed("暂无数据");
        }

        List<ImsInvoice> collect = invoices.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        List<String> ids = collect.stream().map(ImsInvoice::getPkNch).collect(Collectors.toList());
        if (ids.isEmpty()) return CommonResult.failed();
        // 查出单据对应的单据明细
        List<ImsInvoiceItem> items = imsInvoiceItemService.listByBillIds(ids);

        List<InvoiceDto> dtos = new ArrayList<>();
        collect.forEach(i -> {
            InvoiceDto dto = new InvoiceDto();
            BeanUtils.copyProperties(i, dto);
            dto.setInvoiceItems(items.stream().filter(is -> is.getBillSn().equals(dto.getBillSn())).collect(Collectors.toList()));
            dto.setCreateTime(i.getCreateTime());
            dtos.add(dto);
        });

        Map<String, Object> result = new HashMap<>();
        // mp的分页插件用不了 只能自己分页
        result.put("list", dtos);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("total", invoices.size());

        return CommonResult.success(result);
    }

    /**
     * 合并
     * @param ids@return
     * @return
     */
    @Override
    public CommonResult<String> merge(List<String> ids) {
        List<String> deletedi=new ArrayList<>();
        StringBuffer noto=new StringBuffer();
        int index=0;
        int status = -1;
        ArrayList<String> arrayList=new ArrayList<String>();
        if(ids.size()<2){
            return CommonResult.failed("至少要两条或两条以上的单据才可以合并");
        }
        List<ImsInvoice> invoices = baseMapper.selectBatchIds(ids);
        for (ImsInvoice imsInvoice: invoices) {
            if(!invoices.get(0).getDjlx().equals(imsInvoice.getDjlx())){
                return CommonResult.failed("单据的单据类型不相同,不可以合并");
            }
            if(!invoices.get(0).getPkNccust().equals(imsInvoice.getPkNccust())){
                return CommonResult.failed("单据的客户不相同,不可以合并");
            }
            if(!invoices.get(0).getSellerSn().equals(imsInvoice.getSellerSn())){
                return CommonResult.failed("单据的组织,不可以合并");
            }
            if (imsInvoice.getNote()!=null){
                noto.append(imsInvoice.getNote());
                if (ids.size()-1!=index){
                    noto.append("*");
                }
            }
            if (!ids.get(index).equals(invoices.get(0).getId())){
                deletedi.add(ids.get(index));
            }

            if (status==-1){
                status = imsInvoice.getStatus();
            }else {
                if (status!=imsInvoice.getStatus()){
                    return CommonResult.failed("单据的状态不同，不可以合并");
                }
            }
            arrayList.add(imsInvoice.getDef10());
            index++;
        }
        StringBuffer stringBuffer=new StringBuffer(); //合并记录合并的主键
        for (int i=0;i<arrayList.size();i++) {
            stringBuffer.append(arrayList.get(i));

            if (i<arrayList.size()-1){
                stringBuffer.append(",");
            }
        }
        List<String> pkNcs = invoices.stream().map(ImsInvoice::getId).collect(Collectors.toList());
        List<ImsInvoiceItem> items = imsInvoiceItemService.list(
                new LambdaQueryWrapper<ImsInvoiceItem>().
                    in(ImsInvoiceItem::getManualId, pkNcs).
                    eq(ImsInvoiceItem::getStatus,status));
        //List<ImsInvoiceItem> items= imsInvoiceItemService.listByBillIds(ids);
        BigDecimal jshj=new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);//价税合计
        BigDecimal wsje=new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);//无税金额
        BigDecimal taxAmout=new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);//税额
        for (ImsInvoiceItem item: items) {
            jshj = jshj.add(item.getTaxAmount().setScale(2, BigDecimal.ROUND_HALF_UP));//子表的价税合计
            wsje = wsje.add(item.getWsje().setScale(2, BigDecimal.ROUND_HALF_UP));//子表的无税金额
            taxAmout = taxAmout.add(item.getTaxQuota().setScale(2, BigDecimal.ROUND_HALF_UP));//子表的税额
            item.setBillId(invoices.get(0).getId());
            item.setManualId(invoices.get(0).getId());
            item.setPkNch(invoices.get(0).getPkNch());
            item.setBillSn(invoices.get(0).getBillSn());
        }
        invoices.get(0).setPayAmount(jshj);
        invoices.get(0).setWsje(wsje);
        invoices.get(0).setTaxAmount(taxAmout);
        invoices.get(0).setDef10(stringBuffer.toString());
        //保存修改
        baseMapper.updateById(invoices.get(0));
        imsInvoiceItemService.updateBatchById(items);
        //删除其他表头
        QueryWrapper<ImsInvoice> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("id",deletedi);
        baseMapper.delete(queryWrapper);
        return CommonResult.success("退回成功");
    }

    @Override
    public CommonResult<String> deleteInvoice(List<String> ids) {
        List<ImsInvoice> invoices = baseMapper.selectBatchIds(ids);
        long num = invoices.stream().filter(invoice -> invoice.getStatus() != InvoiceStatusEnums.NOT.getCode()).count();
        if (num != 0) return CommonResult.failed("存在非未开票状态的单据,不能删除");

        //查询出子表
        for (ImsInvoice invoice:invoices) {
            List<ImsInvoiceItem> invoiceItems = imsInvoiceItemService.list(new LambdaQueryWrapper<ImsInvoiceItem>()
                    .eq(ImsInvoiceItem::getManualId, invoice.getId())
                    .eq(ImsInvoiceItem::getStatus,invoice.getStatus())
            );

            long num0 = invoiceItems.stream().filter(invoiceItem -> invoiceItem.getStatus() != InvoiceStatusEnums.NOT.getCode()).count();
            if (num0 != 0) return CommonResult.failed("存在非未开票状态的单据,不能删除");

            //发票和发票明细都是未开票，那么就直接修改状态为-1
            invoice.setStatus(-1);
            updateById(invoice);
            List<ImsInvoiceItem> imsInvoiceItems = invoiceItems.stream().map(invoiceItem -> {
                invoiceItem.setStatus(-1);
                return invoiceItem;
            }).collect(Collectors.toList());
            imsInvoiceItemService.updateBatchById(imsInvoiceItems);
        }

        return CommonResult.success("删除成功");
    }

    @Override
    public CommonResult<String> returnInvoice(List<String> ids) {
        List<ImsInvoice> invoices = baseMapper.selectBatchIds(ids);
        long num = invoices.stream().filter(invoice -> invoice.getStatus() != InvoiceStatusEnums.NOT.getCode()).count();
        if (num != 0) return CommonResult.failed("存在非未开票状态的单据,不能退回");
//        pushBillService.pushReturn(invoices);
        // 储存退回记录
        returnInvoiceSer.add(invoices);
        // 修改状态，退回后状态改为return？默认查询增加查询已回退的
        List<ImsInvoice> peek = invoices.stream().peek(i -> i.setStatus(InvoiceStatusEnums.RETURN.getCode())).collect(Collectors.toList());
        updateBatchById(peek);
//        List<ImsInvoiceItem> imsInvoiceItems = imsInvoiceItemService.listByBillIds(invoices.stream().map(ImsInvoice::getId).collect(Collectors.toList()));
//        List<ImsInvoiceItem> peek = imsInvoiceItems.stream().peek(i -> i.setStatus(InvoiceStatusEnums.RETURN.getCode())).collect(Collectors.toList());
//        imsInvoiceItemService.updateBatchById(peek);

        return CommonResult.success("退回成功");
    }

    @Override
    public boolean updateStatusBySn(int code, List<String> billSn) {
        if (CollUtil.isEmpty(billSn)) return false;
        else return baseMapper.updateStatusBySn(code, billSn);
    }

    @Override
    public CommonResult invoiceInfo(String id) {
        ImsInvoice i = baseMapper.selectById(id);
        InvoiceDto dto = new InvoiceDto();
        BeanUtil.copyProperties(i, dto);
        //List<ImsInvoiceItem> items = imsInvoiceItemService.listByBillIds(Collections.singletonList(id));
        List<ImsInvoiceItem> invoiceItems = imsInvoiceItemService.list(new LambdaQueryWrapper<ImsInvoiceItem>()
                .eq(ImsInvoiceItem::getManualId, id)
                .eq(ImsInvoiceItem::getStatus, i.getStatus())
                .last(" ORDER BY CAST(DEF6 AS number)")
        );
        List<ImsInvoiceItem> items = getInvoiceItemConfigName(invoiceItems);
        dto.setInvoiceItems(items);
        dto.setCreateTime(i.getCreateTime());
        Map<String, Object> result = new HashMap<>();

        List<ImsReturnInvoiceParam> listByBillSn = returnInvoiceSer.getListByBillSn(i.getBillSn());//暂时没有用上，不做修改
        result.put("info", dto);
        result.put("re", listByBillSn);
        return CommonResult.success(result);
    }

    @Override
    public boolean updateStatusApply(String id, String name, String code, int billType, double applyje,int status,int contain) {
        baseMapper.updateStatusApply(status,id,name, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),code,billType,applyje,contain);
        return false;
    }

    @Override
    public CommonResult<String> cancel(List<String> ids, Principal principal) {
        //根据发票id从主表中查询出发票，
        List<ImsInvoice> invoices = list(new LambdaQueryWrapper<ImsInvoice>()
                .in(ImsInvoice::getId, ids)
        );
        long n0 = invoices.stream().filter(f -> f.getStatus() != InvoiceStatusEnums.SUCCESS.getCode()).count();
        if (n0 > 0) return CommonResult.failed("发票未成功开票,不能作废!");

        long n1 = invoices.stream().filter(b -> !DateUtil.isSameMonth(DateUtil.parse(b.getCreateTime()), DateUtil.date())).count();
        if (n1 > 0) return CommonResult.failed("跨月发票不能作废!");

        //在作废表和作废明细表中添加记录

        for (ImsInvoice bill: invoices) {
            String[] a= bill.getBillNo().split("/");
            if(bill.getBillType()==3||bill.getBillType()==4){


                Map resultMap=null;
                for (int i = 0; i < a.length; i++) {
                    Map<String, String> dto = new HashMap<>();
                    dto.put("fpDm", bill.getBillCode());
                    dto.put("fpHm", bill.getBillNo());

                    GsonBuilder builder = new GsonBuilder();
                    Map<String, String> paramsMap = new HashMap<>();
                    paramsMap.put("requestdatas", builder.create().toJson(dto));

                    LOGGER.info("作废接口参数报文:   " + paramsMap);

                    resultMap = openBillBuilder.callInvoiceApply(DOMAIN + CANCEL_URL + APP_ID, paramsMap);
                    LOGGER.info("作废接口返回报文:   " + resultMap);
                }

                if (resultMap.get("code").equals("0000")){
                    LambdaUpdateWrapper<ImsInvoice> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper.eq(ImsInvoice::getId, bill.getId())
                            .eq(ImsInvoice::getStatus,InvoiceStatusEnums.SUCCESS.getCode())
                            .set(ImsInvoice::getStatus, InvoiceStatusEnums.NOT.getCode())
                            .set(ImsInvoice::getCreateTime, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    update(null,lambdaUpdateWrapper);
                    LambdaUpdateWrapper<ImsInvoiceItem> lambdaUpdateWrapper1=new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper1.eq(ImsInvoiceItem::getManualId, bill.getId())
                            .eq(ImsInvoiceItem::getStatus,InvoiceStatusEnums.SUCCESS.getCode())
                            .set(ImsInvoiceItem::getStatus, InvoiceStatusEnums.NOT.getCode())
                            .set(ImsInvoiceItem::getCreateTime, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    imsInvoiceItemService.update(null,lambdaUpdateWrapper1);
                    imsCancleInvoiceService.add(invoices,principal);
                    return CommonResult.success("作废成功");
                }else {
                    return  CommonResult.failed("单据号【"+bill.getBillSn()+"】"+resultMap.get("msg")+"，作废失败");
                }
            }else{
                List<Object> dtos = new ArrayList<>();
                for (int i = 0; i < a.length; i++) {
                    Map<String, Object> dto = new HashMap<>();
                    String serial = OpenBillBuilder.createSerialNumber();
                    bill.setBillSerial(serial);
                    if (i==0){
                        bill.setDef7(serial);
                    }else {
                        bill.setDef7(serial+"/"+bill.getDef7());
                    }
                    dto.put("FPQQLSH", serial);
                    dto.put("fpDm", "");
                    dto.put("fpHm", bill.getBillNo());
                    dto.put("hzxxbbh",bill.getRedapplycode());
                    dto.put("HCYY","2");
                    // dto.put("ALLELCUSERNAME",null);
//                  dto.put("ALLELCPASSWORD",null);
                    dtos.add(dto);
                }
//            Map<String, Object> phone = new HashMap<>();
//            phone.put("fpqqlsh", serial);
//            phone.put("address", CALLBACK_PHONE);
//            phones.add(phone);
//
//            Map<String, Object> email = new HashMap<>();
//            email.put("fpqqlsh", serial);
//            email.put("address", CALLBACK_EMAIL);
//            emails.add(email);


            GsonBuilder builder = new GsonBuilder();

            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put("requestdatas", builder.create().toJson(dtos));

            paramsMap.put("autoAudit", "true");

            LOGGER.info("专票红冲作废接口参数报文:   " + paramsMap);

            Map<String, String> resultMap = openBillBuilder.callInvoiceApply(DOMAIN + RED_URL + APP_ID, paramsMap);
            LOGGER.info("专票红冲作废接口返回报文:   " + resultMap);

            if (resultMap.get("code").equals("0000")){
                    LambdaUpdateWrapper<ImsInvoice> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper.eq(ImsInvoice::getId, bill.getId())
                            .eq(ImsInvoice::getStatus,InvoiceStatusEnums.SUCCESS.getCode())
                            .set(ImsInvoice::getStatus, InvoiceStatusEnums.NOT.getCode())
                            .set(ImsInvoice::getCreateTime, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    update(null,lambdaUpdateWrapper);
                    LambdaUpdateWrapper<ImsInvoiceItem> lambdaUpdateWrapper1=new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper1.eq(ImsInvoiceItem::getManualId, bill.getId())
                            .eq(ImsInvoiceItem::getStatus,InvoiceStatusEnums.SUCCESS.getCode())
                            .set(ImsInvoiceItem::getStatus, InvoiceStatusEnums.NOT.getCode())
                            .set(ImsInvoiceItem::getCreateTime, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    imsInvoiceItemService.update(null,lambdaUpdateWrapper1);
                    imsCancleInvoiceService.add(invoices,principal);
                    return CommonResult.success("作废成功");
                }else {
                    return  CommonResult.failed("单据号【"+bill.getBillSn()+"】"+resultMap.get("msg")+"，作废失败");
                }


            }


        }
        return CommonResult.failed("作废失败");
    }

    @Override
    public String updateBySerial(CallbackInvoiceParam param) {

        QueryWrapper<ImsInvoice> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ImsInvoice> lambda = wrapper.lambda();
        lambda.eq(ImsInvoice::getBillSerial, param.getFpqqlsh());
        ImsInvoice one = getOne(wrapper);
        if (BeanUtil.isEmpty(one)) return "根据流水号未查出发票信息";

        Gson gson = new Gson();
        CallbackInvoiceData data = gson.fromJson(param.getData(), CallbackInvoiceData.class);

        if ("0000".equals(param.getCode())) {
            one.setStatus(InvoiceStatusEnums.SUCCESS.getCode());
//            one.setExtractUrl(param.getShareurl());
//            one.setExtractCode(param.getSharecode());
//            one.setBillNo(data.getFpHm());
//            one.setBillCode(data.getFpDm());
        } else one.setStatus(InvoiceStatusEnums.FAILED.getCode());

        return String.valueOf(updateById(one));
    }

    /**
     * 合并操作去哪了
     * @param ids
     * @return
     */
    @Override
    public CommonResult<Map<String, Object>> mergeList(List<String> ids) {
        List<ImsInvoice> invoices = list(new LambdaQueryWrapper<ImsInvoice>()
                .in(ImsInvoice::getId, ids)
                .eq(ImsInvoice::getStatus, InvoiceStatusEnums.NOT.getCode())
        );
        if (invoices.size()==0) return CommonResult.failed("未查询到单据信息");

        // 查出单据对应的单据明细
        //List<ImsInvoiceItem> items = imsInvoiceItemService.listByBillIds(ids);
        List<ImsInvoiceItem> items = imsInvoiceItemService.list(new LambdaQueryWrapper<ImsInvoiceItem>()
                .in(ImsInvoiceItem::getManualId, ids)
                .eq(ImsInvoiceItem::getStatus, InvoiceStatusEnums.NOT.getCode())
        );

        List<InvoiceDto> dtos = new ArrayList<>();
        invoices.forEach(i -> {
            InvoiceDto dto = new InvoiceDto();
            BeanUtils.copyProperties(i, dto);
            //dto.setInvoiceItems(items.stream().filter(is -> is.getBillSn().equals(dto.getBillSn())).collect(Collectors.toList()));
            dto.setInvoiceItems(items.stream().filter(is -> is.getManualId().equals(dto.getId())).collect(Collectors.toList()));
            dto.setCreateTime(i.getCreateTime());
            dtos.add(dto);
        });
        Map<String, Object> result = new HashMap<>();
        // mp的分页插件用不了 只能自己分页
        result.put("list", dtos);
        result.put("total", invoices.size());
        return CommonResult.success(result);
    }

    @Override
    public CommonResult<Map<String, Object>> applyList(String username,List<String> ids) {
        UmsAdmin umsAdmin = adminService.getAdminByUsername(username);
        Boolean isKF = false;
        if(umsAdmin!=null){
            List<UmsAdminRoleRelation> list = umsAdminRoleRelationService.list(new LambdaQueryWrapper<UmsAdminRoleRelation>().eq(UmsAdminRoleRelation::getAdminId, umsAdmin.getId()));
            if(list!=null&&list.size()>0){
                for (UmsAdminRoleRelation umsAdminRoleRelation: list) {
                    if ("10".equals(umsAdminRoleRelation.getRoleId())){
                        isKF = true;
                    }
                }
            }

        }
        if (isKF){
            return CommonResult.failed("客服用户无数据操作权限");
        }

        List<ImsInvoice> invoices = list(new LambdaQueryWrapper<ImsInvoice>()
                .in(ImsInvoice::getId, ids)
                .eq(ImsInvoice::getStatus, InvoiceStatusEnums.APPLY.getCode())
        );
        if (invoices.size()==0) return CommonResult.failed("未查询到单据信息");

        // 查出单据对应的单据明细
        //List<ImsInvoiceItem> items = imsInvoiceItemService.listByBillIds(ids);
        List<ImsInvoiceItem> items = imsInvoiceItemService.list(new LambdaQueryWrapper<ImsInvoiceItem>()
                        .in(ImsInvoiceItem::getManualId, ids)
                .eq(ImsInvoiceItem::getStatus, InvoiceStatusEnums.NOT.getCode())
        );

        List<InvoiceDto> dtos = new ArrayList<>();
        invoices.forEach(i -> {
            InvoiceDto dto = new InvoiceDto();
            BeanUtils.copyProperties(i, dto);
            //dto.setInvoiceItems(items.stream().filter(is -> is.getBillSn().equals(dto.getBillSn())).collect(Collectors.toList()));
            dto.setInvoiceItems(items.stream().filter(is -> is.getManualId().equals(dto.getId())).collect(Collectors.toList()));
            dto.setCreateTime(i.getCreateTime());
            dtos.add(dto);
        });
        Map<String, Object> result = new HashMap<>();
        // mp的分页插件用不了 只能自己分页
        result.put("list", dtos);
        result.put("total", invoices.size());
        return CommonResult.success(result);
    }

    @Override
    public XSSFWorkbook downLoadPageNumInvoice(String username, Integer pageSize, Integer pageNum,String billSerial, String billSn,String billNo,String billCode, String sellerName, String buyerName, Integer status, String startTime, String endTime,String djlx) {
        try {
            XSSFWorkbook wb = new XSSFWorkbook();//在内存中创建excel文件
            XSSFSheet sheet = wb.createSheet("开票信息");//创建工作页
            XSSFRow row = sheet.createRow(0);//创建表头
            row.createCell(0).setCellValue("单据号");//billSn
            row.createCell(1).setCellValue("发票号");//billNo
            row.createCell(2).setCellValue("发票类型");//billType
            row.createCell(3).setCellValue("发票代码");//billCode
            row.createCell(4).setCellValue("单据日期");//createTime
            row.createCell(5).setCellValue("客户名称");//buyerName
            row.createCell(6).setCellValue("开票组织");//sellerName
            row.createCell(7).setCellValue("应收类型");//djlx
            row.createCell(8).setCellValue("税额");//taxAmount
            //row.createCell(9).setCellValue("开票金额");//applyje
            row.createCell(9).setCellValue("无税合计");//wsje
            row.createCell(10).setCellValue("开票状态");//status
            row.createCell(11).setCellValue("备注");//note
            row.createCell(12).setCellValue("开票日期");//applydate
            row.createCell(13).setCellValue("开票人");//applydate
            row.createCell(14).setCellValue("流水号");//billSerial

            // 根据开票通知上面的公司和登录用户勾选的公司，当前登录人只展示自己对应的公司开票信息。
            UmsAdmin umsAdmin = adminService.getAdminByUsername(username);
            List<String> partyIds = umsAdminOrgRelationService.getNcOrgByAdminId(umsAdmin.getId());
            QueryWrapper<ImsInvoice> wrapper = new QueryWrapper<>();
            LambdaQueryWrapper<ImsInvoice> lambda = wrapper.lambda();
            if (!username.equals("admin") && CollUtil.isNotEmpty(partyIds)) {
                List<UmsNcOrg> parties = orgService.listByIds(partyIds);
                lambda.in(ImsInvoice::getSellerSn, parties.stream().map(UmsNcOrg::getCode).collect(Collectors.toList()));
            }
            if (StrUtil.isNotEmpty(billSerial)) lambda.like(ImsInvoice::getBillSerial, billSerial);
            if (StrUtil.isNotEmpty(billSn)) lambda.like(ImsInvoice::getBillSn, billSn);
            if (StrUtil.isNotEmpty(billNo)) lambda.like(ImsInvoice::getBillNo, billNo);
            if (StrUtil.isNotEmpty(billCode)) lambda.like(ImsInvoice::getBillCode, billCode);
            if (StrUtil.isNotEmpty(sellerName)) lambda.like(ImsInvoice::getSellerName, sellerName);
            if(StrUtil.isNotEmpty(umsAdmin.getNcid()))lambda.like(ImsInvoice::getDef5,umsAdmin.getNcid());
            if (StrUtil.isNotEmpty(buyerName)) lambda.like(ImsInvoice::getBuyerName, buyerName);
            if (djlx != null) {
                lambda.eq(ImsInvoice::getDjlx, djlx);
            } else {
                lambda.in(ImsInvoice::getDjlx,"fp","ys","lp" );
            }
            if (status==null){
                lambda.in(ImsInvoice::getStatus,2);
            }else {
                lambda.in(ImsInvoice::getStatus, status);
            }
            if (StrUtil.isNotBlank(startTime))
                lambda.ge(ImsInvoice::getCreateTime, DateUtil.parse(startTime, DatePattern.NORM_DATE_FORMAT));
            if (StrUtil.isNotBlank(endTime))
                lambda.le(ImsInvoice::getCreateTime, DateUtil.parse(endTime, DatePattern.NORM_DATE_FORMAT));
            lambda.last("order by case status when 3 then 1 when 1 then 2 when 4 then 3 when 7 then 4 else 5 end ,create_time desc");
            List<ImsInvoice> invoices = list(wrapper);
            if (invoices.isEmpty()) {
                //return CommonResult.validateFailed("暂无数据");
            }

            List<ImsInvoice> collect = invoices.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());

            int rowNumber = 1;
            for (ImsInvoice imsInvoice : invoices) {
                row = sheet.createRow(rowNumber);
                if (imsInvoice.getBillSn()!=null){
                    row.createCell(0).setCellValue(imsInvoice.getBillSn());//billNo
                }
                if (imsInvoice.getBillNo()!=null){
                    row.createCell(1).setCellValue(imsInvoice.getBillNo());//billNo
                }
                if (imsInvoice.getBillType()!=null){
                    row.createCell(2).setCellValue(ImsInvoiceUtil.getBillTypeName(imsInvoice.getBillType()));//billType
                }
                if (imsInvoice.getBillCode()!=null){
                    row.createCell(3).setCellValue(imsInvoice.getBillCode());//billCode
                }
                if (imsInvoice.getCreateTime()!=null){
                    row.createCell(4).setCellValue(imsInvoice.getCreateTime());//createTime
                }
                if (imsInvoice.getBuyerName()!=null){
                    row.createCell(5).setCellValue(imsInvoice.getBuyerName());//buyerName
                }
                if (imsInvoice.getSellerName()!=null){
                    row.createCell(6).setCellValue(imsInvoice.getSellerName());//sellerName
                }
                if (imsInvoice.getDjlx()!=null){
                    row.createCell(7).setCellValue(ImsInvoiceUtil.getDjlxName(imsInvoice));//djlx
                }if (imsInvoice.getTaxAmount()!=null){
                    row.createCell(8).setCellValue(imsInvoice.getTaxAmount().doubleValue());//taxAmount
                }/*if (imsInvoice.getApplyje()!=null){
                    row.createCell(9).setCellValue(imsInvoice.getApplyje().doubleValue());//applyje
                }*/if (imsInvoice.getWsje()!=null){
                    row.createCell(9).setCellValue(imsInvoice.getWsje().doubleValue());//wsje
                }
                if (imsInvoice.getStatus()!=null){
                    row.createCell(10).setCellValue(ImsInvoiceUtil.getStatusName(imsInvoice.getStatus()));//status
                }if (imsInvoice.getNote()!=null){
                    row.createCell(11).setCellValue(imsInvoice.getNote());//note
                }if (imsInvoice.getApplydate()!=null){
                    row.createCell(12).setCellValue(imsInvoice.getApplydate());//applydate
                }if (imsInvoice.getApplyname()!=null){
                    row.createCell(13).setCellValue(imsInvoice.getApplyname());//applyname
                }if (imsInvoice.getBillSerial()!=null){
                    row.createCell(14).setCellValue(imsInvoice.getBillSerial());//billSerial
                }
                rowNumber++;
            }
            return wb;
        } catch (Exception ioException) {
            ioException.printStackTrace();
            return null;
        }
    }


}
